/** <a href="http://www.cpupk.com/decompiler">Eclipse Class Decompiler</a> plugin, Copyright (c) 2017 Chen Chao. **/
package com.minierp.validator;

import com.minierp.bean.ProductTypeBean;
import com.minierp.dao.ProductTypeDao;
import com.minierp.model.ProductType;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

public class ProductTypeValidator implements Validator {
	private ProductTypeDao productTypeDao;

	public boolean supports(Class clazz) {
		return ProductTypeBean.class.isAssignableFrom(clazz);
	}

	public void validate(Object obj, Errors errors) {
		ProductTypeBean form = (ProductTypeBean) obj;
		boolean hasError = false;
		ProductType d;
		if (form.getCodeRule().getGenerateRule().equals("MANUAL")
				|| form.getProductType().getId() != 0L) {
			if (form.getProductType().getTypeCode() != null
					&& !form.getProductType().getTypeCode().trim().equals("")) {
				d = this.productTypeDao
						.get(form.getProductType().getTypeCode());
				if (d != null && d.getId() != form.getProductType().getId()) {
					errors.rejectValue("productType.typeCode", "", "『编号』已经存在");
					hasError = true;
				}
			} else {
				errors.rejectValue("productType.typeCode", "", "请输入『编号』");
				hasError = true;
			}
		}

		if (!hasError) {
			if (form.getProductType().getTypeName() != null
					&& !form.getProductType().getTypeName().trim().equals("")) {
				if (form.getProductType().getParentId() != 0L
						&& form.getProductType().getId() != 0L) {
					if (form.getProductType().getParentId() == form
							.getProductType().getId()) {
						errors.rejectValue("productType.parentId", "",
								"不能选择自己作为『上级类别』");
					} else {
						d = (ProductType) this.productTypeDao.get(
								ProductType.class, form.getProductType()
										.getParentId());
						if (d != null
								&& d.getParentIdStr() != null
								&& d.getParentIdStr().indexOf(
										";" + form.getProductType().getId()
												+ ";") != -1) {
							errors.rejectValue("productType.parentId", "",
									"不能选择自己的下级作为『上级类别』");
						}
					}
				}
			} else {
				errors.rejectValue("productType.typeName", "", "请输入『名称』");
			}
		}

	}

	public ProductTypeDao getProductTypeDao() {
		return this.productTypeDao;
	}

	public void setProductTypeDao(ProductTypeDao productTypeDao) {
		this.productTypeDao = productTypeDao;
	}
}